import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { DatePipe } from '@angular/common';
import { Observable,Operator } from "rxjs";
import { Environment } from "environments/environment";
import { NavHeaderService } from "@global/layout/default/nav-header/nav-header.service";
import { FcsServiceStartupService } from './fcs-service-startup.service';
import { map } from 'rxjs/operators';

@Injectable( {providedIn: 'root'} )
export class FcsStatusService {

  constructor(private http: HttpClient,
              private navHeaderService: NavHeaderService,
              private datePipe: DatePipe) { }

  /**
   * 检查函数计算服务是否开通 - 调用企业云接口.
   */
  checkFCSServiceState(userId: string): Promise<any> {
    return this.http
      .get(Environment.application.bssAPI + '/order/', {
        params: {
          userId: userId,
          productLineCode: 'FCS',
          orderStatus: 'paySuccess'
        }
      })
      .toPromise();
  }

  /**
   * 订单接口 
   */
   checkFCSOrder(userId: string): Promise<any> {
    return this.http
      .get(Environment.application.bssAPI + '/order/orders/'+ userId).toPromise();
  }

  /**
   * 检查FCS服务暂停状态 - 调用FCS接口.
   * //this.navHeaderService.getCurrentRegion() +
   */
  checkFcsSuspendStatus(): Promise<any> {
    return this.http
      .get('/ifcs/v1/user-status')
      .toPromise();
  }

  /**
   * 开通函数计算服务 - 调用企业云接口.
   */
  approveFcsService(userId: string, token: string,region:string): Promise<any> {
    const UUID = require('uuid/v4');
    const FCS_IA = {
      region: region,
      availableZone: '',
      productLineCode: 'FCS',
      productTypeCode: 'FCS',
      productName: '函数计算',
      instanceCount: 1,
      itemList: [
        {
          code: 'call_times',
          value: '0'
        },
        {
          code: 'resource_usage',
          value: '0'
        },
        {
          code: 'egress_traffic',
          value: '0'
        }
      ]
    };
    const FCS = {
      instanceId: UUID(),
      region: region,
      availableZone: '',
      productLineCode: 'FCS',
      productTypeCode: 'FCS',
      productName: '函数计算',
      instanceCount: 1,
      itemList: [
        {
          code: 'call_times',
          value: '0'
        },
        {
          code: 'resource_usage',
          value: '0'
        },
        {
          code: 'egress_traffic',
          value: '0'
        }
      ]
    };
    let body = {
      userId: userId,
      token: token,
      orderRoute: 'FCS',
      setCount: 1,
      consoleOrderFlowId: UUID(),
      billType: 'dailyNetflow',
      duration: '1',
      durationUnit: 'H',
      orderWhat: 'formal',
      orderSource: 'console',
      orderType: 'new',
      serviceStartTime: this.datePipe.transform(
        new Date(),
        'yyyy-MM-dd HH:mm:ss'
      ),
      serviceEndTime: '2099-12-31 23:59:59',
      isAutoDeducted: false,
      isAutoRenew: false,
      // rewardActivity: '',
      // totalMoney: '0',
      consoleCustomization: {},
      productList: [
        FCS
      ]
    };
    // let isIncludesOssIa = FcsServiceStartupService.storageClassList.some((val, idx, array) => {
    //   return val.code === FcsServiceStartupService.STORAGECLASS.STANDARD_IA;
    // });

    // if (isIncludesOssIa) {
    //   body.productList.push(FCS_IA);
    // }

    //为进行漏洞修复对内容进行了构造
    return this.http
        .post(Environment.application.bssAPI + '/order/confirm', body)
        .pipe(
            map(response => {
              // 白名单过滤返回字段
              const allowedFields = ['orderId', 'status', 'message', 'orderNumber'];
              const sanitizedResponse: any = {};

              for (const field of allowedFields) {
                if (response.hasOwnProperty(field)) {
                  // 验证数值字段在安全范围内
                  if (field === 'orderId' && typeof response[field] === 'string') {
                    sanitizedResponse[field] = response[field];
                  } else if (field === 'status' && typeof response[field] === 'string') {
                    // 使用白名单验证状态值
                    const validStatuses = ['success', 'pending', 'failed'];
                    if (validStatuses.includes(response[field])) {
                      sanitizedResponse[field] = response[field];
                    } else {
                      sanitizedResponse[field] = 'unknown'; // 默认安全值
                    }
                  } else {
                    sanitizedResponse[field] = response[field];
                  }
                }
              }
              return sanitizedResponse;
            })
        )
        .toPromise();

  }

}
